package com.z.pms1.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.z.pms1.dao.MenuDao;
import com.z.pms1.model.C_menu;
import com.z.pms1.service.MenuService;
import com.z.pms1.vo.MenuVo;

@Service("menuService")
public class MenuServiceImpl implements MenuService {

	@Autowired
	private MenuDao menuDao;
	
	public List<MenuVo> treegrid() {
		List<C_menu> c_menuList = menuDao.allMenuList();
		List<MenuVo> menuVoList = new ArrayList<MenuVo>();
		if (null != c_menuList && c_menuList.size() > 0) {
			for (C_menu c : c_menuList) {
				MenuVo vo = new MenuVo();
				BeanUtils.copyProperties(c, vo);
				if (null != c.getC_menu()) {
					vo.setPid(c.getC_menu().getId());
					vo.setPname(c.getC_menu().getText());
				}
				vo.setIconCls(c.getIconCls());
				menuVoList.add(vo);
			}
		}
		return menuVoList;
	}

	public List<MenuVo> allTreeNode() {
		List<C_menu> c_menuList = menuDao.allMenuList();
		List<MenuVo> menuVoList = new ArrayList<MenuVo>();
		if (null != c_menuList && c_menuList.size() > 0) {
			for (C_menu c : c_menuList) {
				MenuVo vo = new MenuVo();
				BeanUtils.copyProperties(c, vo);
				Map<String, Object> attributes = new HashMap<String, Object>();
				attributes.put("url", c.getUrl());
				vo.setAttributes(attributes);
				if (null != c.getC_menu()) {
					vo.setPid(c.getC_menu().getId());
				}
				vo.setIconCls(c.getIconCls());
				menuVoList.add(vo);
			}
		}
		return menuVoList;
	}

	public MenuVo edit(MenuVo menuVo) {
		C_menu c_menu = menuDao.get(menuVo.getId());
		if (null != c_menu) {
			BeanUtils.copyProperties(c_menu, menuVo);
			c_menu.setIconCls(menuVo.getIconCls());
			c_menu.setC_menu(null);
			if (menuVo.getPid() != null 
					&& !menuVo.getPid().trim().equals("") 
					&& !menuVo.getPid().equals(menuVo.getId())) {
				C_menu c = menuDao.get(menuVo.getPid());
				if (c != null) {
					if (isDown(c_menu, c)) {
						Set<C_menu> c_menuSet = c_menu.getC_menuSet();
						if (c_menuSet != null && c_menuSet.size() > 0) {
							for (C_menu m : c_menuSet) {
								if (m != null) {
									m.setC_menu(null);
								}
							}
						}
					}
					c_menu.setC_menu(c);
				}
			}
		}
		return menuVo;
	}
	
	private boolean isDown(C_menu t, C_menu pt) {
		if (pt.getC_menu() != null) {
			if (pt.getC_menu().getId().equals(t.getId())) {
				return true;
			} else {
				return isDown(t, pt.getC_menu());
			}
		}
		return false;
	}

}